// utils/BufferUtil.ets
import util from '@ohos.util';

export class BufferUtil {
  /**
   * Uint8Array 转 ArrayBuffer
   */
  static uint8ArrayToArrayBuffer(uint8Array: Uint8Array): ArrayBuffer {
    if (uint8Array.byteOffset === 0 && uint8Array.byteLength === uint8Array.buffer.byteLength) {
      return uint8Array.buffer;
    }
    return uint8Array.buffer.slice(
      uint8Array.byteOffset,
      uint8Array.byteOffset + uint8Array.byteLength
    );
  }

  /**
   * ArrayBuffer 转 Uint8Array
   */
  static arrayBufferToUint8Array(arrayBuffer: ArrayBuffer): Uint8Array {
    return new Uint8Array(arrayBuffer);
  }

  /**
   * Base64 转 Uint8Array
   */
  static base64ToUint8Array(base64String: string): Uint8Array {
    const base64 = new util.Base64();
    return base64.decodeSync(base64String);
  }

  /**
   * 合并多个 Uint8Array
   */
  static concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
    const totalLength = arrays.reduce((acc, arr) => acc + arr.length, 0);
    const result = new Uint8Array(totalLength);
    let offset = 0;
    for (const arr of arrays) {
      result.set(arr, offset);
      offset += arr.length;
    }
    return result;
  }

  /**
   * 检查是否是完整的 ArrayBuffer
   */
  static isCompleteArrayBuffer(uint8Array: Uint8Array): boolean {
    return uint8Array.byteOffset === 0 &&
      uint8Array.byteLength === uint8Array.buffer.byteLength;
  }
}